<template>
  <div>
    <div ref="myChart" :style="{ height: `${height}px`, width: `100%` }"></div>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, onUnmounted, watch } from 'vue';
import { ref } from 'vue';
import echarts, { ECharts } from 'echarts';
import { addListener, removeListener } from 'resize-detector';
import dark from '@/components/chart/dark';
import { debounce } from 'lodash-es';
echarts.registerTheme('dark-pro', dark);
export default defineComponent({
  props: {
    height: {
      type: Number,
      default: 200,
    },
    option: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  setup(props) {
    const echartsOption = ref<any>({
      tooltip: {
        trigger: 'item',
      },
      series: [
        {
          type: 'pie',
          radius: [20, '55%'],
          center: ['50%', '50%'],
          data: [],
          roseType: 'radius',
          animationType: 'scale',
          animationEasing: 'elasticOut',
          animationDelay: function () {
            return Math.random() * 200;
          },
        },
      ],
    });
    const myChart = ref<any>();
    let chart: ECharts | null = null;
    const resizeChart = () => {
      chart?.resize();
    };
    const resize = debounce(resizeChart, 300);
    const myCharts = ref<any>();
    const init = () => {
      chart = echarts.init(myChart.value!);
      chart.setOption(echartsOption.value);
      addListener(myChart.value, resize);
    };
    onMounted(() => {
      init();
    });
    watch(
      () => props.option,
      () => {
        echartsOption.value.series[0].data = props.option;
        init();
      },
    );
    onUnmounted(() => {
      if (myChart.value) {
        removeListener(myChart.value, resize);
      }
      chart?.dispose();
      chart = null;
    });
    return {
      echartsOption,
      myChart,
      init,
      myCharts,
      resizeChart,
    };
  },
});
</script>
